package cinema;

import java.util.Date;
import java.util.UUID;
import java.util.Objects;

public class Ticket {
    private final String ticketId;
    private final Movie movie;
    private final Schedule schedule;
    private final String seat;
    private final double price;
    private final Date saleTime;
    private boolean refunded;

    public Ticket(Movie movie, Schedule schedule, String seat, double price) {
        this.ticketId = UUID.randomUUID().toString();
        this.movie = Objects.requireNonNull(movie, "电影信息不能为空");
        this.schedule = Objects.requireNonNull(schedule, "场次信息不能为空");
        this.seat = validateSeatFormat(seat);
        this.price = validatePrice(price);
        this.saleTime = new Date();
        this.refunded = false;
    }

    // 获取票务详细信息
    public String getTicketInfo() {
        return String.format("""
                票号：%s
                影片：%s
                场次：%s
                时间：%s
                座位：%s
                票价：%.2f元
                售票时间：%s
                状态：%s""",
                ticketId,
                movie.getName(),
                schedule.getScheduleId(),
                schedule.getTime(),
                seat,
                price,
                saleTime,
                refunded ? "已退票" : "有效");
    }

    //============ Getter 方法 ============//
    public String getTicketId() {
        return ticketId;
    }

    public Movie getMovie() {
        return movie;
    }

    public Schedule getSchedule() {
        return schedule;
    }

    public String getSeat() {
        return seat;
    }

    public double getPrice() {
        return price;
    }

    public Date getSaleTime() {
        return new Date(saleTime.getTime()); // 返回副本防止外部修改
    }

    public boolean isRefunded() {
        return refunded;
    }

    public void setRefunded(boolean refunded) {
        this.refunded = refunded;
    }

    //============ 辅助方法 ============//
    private double validatePrice(double price) {
        if (price <= 0) {
            throw new IllegalArgumentException("票价必须大于0");
        }
        return price;
    }

    private String validateSeatFormat(String seat) {
        if (seat == null || seat.isEmpty()) {
            throw new IllegalArgumentException("座位信息不能为空");
        }
        if (!seat.matches("\\d+排\\d+号(,\\d+排\\d+号)*")) {
            throw new IllegalArgumentException("座位格式无效，应为'X排Y号'");
        }
        return seat;
    }

    @Override
    public String toString() {
        return getTicketInfo();
    }
}